import {
  IdentityCodeValid,
  checkNameValid,
} from '../common/tool/idCardTool.js';
export const ACTION_SET_TRAINNUMBER = 'SET_TRAINNUMBER';
export const ACTION_SET_DEPARTSTATION = 'SET_DEPARTSTATION';
export const ACTION_SET_ARRIVESTATION = 'SET_ARRIVESTATION';
export const ACTION_SET_SEATTYPE = 'SET_SEATTYPE';
export const ACTION_SET_DEPARTDATE = 'SET_DEPARTDATE';
export const ACTION_SET_ARRIVEDATE = 'SET_ARRIVEDATE';
export const ACTION_SET_DEPARTTIMESTR = 'SET_DEPARTTIMESTR';
export const ACTION_SET_ARRIVETIMESTR = 'SET_ARRIVETIMESTR';
export const ACTION_SET_DURATIONSTR = 'SET_DURATIONSTR';
export const ACTION_SET_PRICE = 'SET_PRICE';
export const ACTION_SET_PASSAGERS = 'SET_PASSAGERS';
export const ACTION_SET_MENU = 'SET_MENU';
export const ACTION_SET_ISMENUVISIBLE = 'SET_ISMENUVISIBLE';
export const ACTION_SET_SEARCHPARSED = 'set_searchParsed';

//action
export function setTrainNumber(trainNumber) {
  return {
    type: ACTION_SET_TRAINNUMBER,
    payload: trainNumber,
  };
}
export function setDepartStation(departStation) {
  return {
    type: ACTION_SET_DEPARTSTATION,
    payload: departStation,
  };
}
export function setArriveStation(arriveStation) {
  return {
    type: ACTION_SET_ARRIVESTATION,
    payload: arriveStation,
  };
}
export function setSeatType(seatType) {
  return {
    type: ACTION_SET_SEATTYPE,
    payload: seatType,
  };
}
export function setDepartDate(departDate) {
  return {
    type: ACTION_SET_DEPARTDATE,
    payload: departDate,
  };
}
export function setArriveDate(arriveDate) {
  return {
    type: ACTION_SET_ARRIVEDATE,
    payload: arriveDate,
  };
}
export function setDepartTimeStr(departTimeStr) {
  return {
    type: ACTION_SET_DEPARTTIMESTR,
    payload: departTimeStr,
  };
}
export function setArriveTimeStr(arriveTimeStr) {
  return {
    type: ACTION_SET_ARRIVETIMESTR,
    payload: arriveTimeStr,
  };
}
export function setDurationStr(durationStr) {
  return {
    type: ACTION_SET_DURATIONSTR,
    payload: durationStr,
  };
}
export function setPrice(price) {
  return {
    type: ACTION_SET_PRICE,
    payload: price,
  };
}
export function setPassagers(passenger) {
  return {
    type: ACTION_SET_PASSAGERS,
    payload: passenger,
  };
}
export function setMenu(menu) {
  return {
    type: ACTION_SET_MENU,
    payload: menu,
  };
}
export function setIsMenuVisible(isMenuVisible) {
  return {
    type: ACTION_SET_ISMENUVISIBLE,
    payload: isMenuVisible,
  };
}
export function setSearchParsed(searchParsed) {
  return {
    type: ACTION_SET_SEARCHPARSED,
    payload: searchParsed,
  };
}

export function fetchInitial(url) {
  return (dispatch, getState) => {
    fetch(url)
      .then((response) => response.json())
      .then((data) => {
        const {
          departTimeStr,
          arriveTimeStr,
          arriveDate,
          durationStr,
          price,
        } = data;

        dispatch(setDepartTimeStr(departTimeStr));
        dispatch(setArriveTimeStr(arriveTimeStr));
        dispatch(setArriveDate(arriveDate));
        dispatch(setDurationStr(durationStr));
        dispatch(setPrice(price));
      });
  };
}
//乘客的业务id
let passengerIdSeed = 0;
//创建成人action
export function createAdult() {
  return (dispatch, getState) => {
    const { passengers } = getState();

    for (const passenger of passengers) {
      if (passenger.ticketType === 'adult') {
        const keys = Object.keys(passenger);
        for (const key of keys) {
          if (!passenger[key]) {
            alert('请先补全乘客信息');
            return;
          }
          const username = passenger['name'];
          if (!username) {
            alert('名字不能为空');
            return;
          }
          if (!checkNameValid(username)) {
            alert('名字不能是纯数字');
            return;
          } // 把和业务相关的放在里面总觉得不太好
          if (!IdentityCodeValid(passenger['licenseNo'])) {
            alert('身份校验不正确');
            return;
          }
        }
      }
    }

    dispatch(
      setPassagers([
        ...passengers,
        {
          id: ++passengerIdSeed,
          name: '',
          ticketType: 'adult',
          licenseNo: '', //成人特有属性
          seat: 'Z',
        },
      ])
    );
  };
}
//创建儿童
export function createChild() {
  return (dispatch, getState) => {
    const { passengers } = getState();
    let adultFound = null;
    for (const passenger of passengers) {
      if (passenger.ticketType === 'adult') {
        const keys = Object.keys(passenger);
        for (const key of keys) {
          if (!passenger[key]) {
            alert('请先补全乘客信息');
            return;
          }
          const username = passenger['name'];
          if (!username) {
            alert('名字不能为空');
            return;
          }
          if (!checkNameValid(username)) {
            alert('名字不能是纯数字');
            return;
          } // 把和业务相关的放在里面总觉得不太好
          if (!IdentityCodeValid(passenger['licenseNo'])) {
            alert('身份校验不正确');
            return;
          }
        }
      }
      if (passenger.ticketType === 'adult') {
        adultFound = passenger.id;
      }
    }
    if (!adultFound) {
      alert('请先添加成人信息');
      return;
    }

    dispatch(
      setPassagers([
        ...passengers,
        {
          id: ++passengerIdSeed,
          name: '',
          ticketType: 'child',
          seat: 'Z',
          gender: 'none', //儿童特有属性
          birth: '', //儿童特有属性
          followAdult: adultFound, //儿童特有属性
        },
      ])
    );
  };
}

export function removePassenger(id) {
  return (dispatch, getState) => {
    const { passengers } = getState();
    const newPassengers = passengers.filter(
      (passenger) => passenger.id !== id && passenger.followAdult !== id
    );
    dispatch(setPassagers(newPassengers));
  };
}
/**
 * 更新 乘客信息
 * @param {*} id
 * @param {*} data
 * @param {*} toRemoveProps 要删除的属性
 */
export function updatePassenger(id, data, toRemoveProps = []) {
  return (dispatch, getState) => {
    const { passengers } = getState();
    for (let i = 0; i < passengers.length; i++) {
      if (id === passengers[i].id) {
        const newPassengers = [...passengers];
        newPassengers[i] = Object.assign({}, passengers[i], data);
        for (const prop of toRemoveProps) {
          delete newPassengers[i][prop];
        }
        // console.log(newPassengers[i]);
        dispatch(setPassagers(newPassengers));
      }
    }
  };
}

export function showMenu(menu) {
  return (dispatch) => {
    dispatch(setMenu(menu));
    dispatch(setIsMenuVisible(true));
  };
}

export function showGenderMenu(id) {
  return (dispatch, getState) => {
    const { passengers } = getState();
    const passenger = passengers.find((p) => p.id === id);
    if (!passenger) {
      console.log('选中的乘客id不存在..');
      return;
    }
    dispatch(
      showMenu({
        onPress: function (gender) {
          dispatch(updatePassenger(id, { gender }));
          dispatch(hideMenu());
        },
        options: [
          {
            title: '男',
            value: 'male',
            active: passenger.gender === 'male',
          },
          {
            title: '女',
            value: 'female',
            active: passenger.gender === 'female',
          },
        ],
      })
    );
  };
}

export function showFollowAdult(id) {
  return (dispatch, getState) => {
    const { passengers } = getState();
    const child = passengers.find((p) => p.id === id);
    //当前的child不存在
    if (!child) return;

    dispatch(
      showMenu({
        onPress: function (passengerId) {
          console.log(passengerId);
          dispatch(updatePassenger(id, { followAdult: passengerId }));
          dispatch(hideMenu());
        },
        options: passengers
          .filter((p) => p.ticketType === 'adult')
          .map((p) => {
            return {
              title: p.name,
              value: p.id,
              active: p.id === child.followAdult,
            };
          }),
      })
    );
  };
}

export function showTicketTypeMenu(id) {
  return (dispatch, getState) => {
    const { passengers } = getState();
    //当前乘客
    let passager = passengers.find((p) => p.id === id);

    dispatch(
      showMenu({
        onPress: function (ticketType) {
          if (ticketType === 'adult') {
            //选择成人票,管它三七二十一,把成人属性加上把儿童属性删除掉
            dispatch(
              updatePassenger(id, { ticketType, licenseNo: '' }, [
                'birth',
                'gender',
                'followAdult',
              ])
            );
          } else {
            //选择儿童票,先判断还有无成人,有成人把成人属性删掉吧儿童属性加上;没有成人,提示先添加成人后才可以修改
            let hasOtherAdult = passengers.find(
              (p) => p.id !== id && p.ticketType === 'adult'
            );
            if (!hasOtherAdult) {
              alert('先添加成人后修改');
            } else {
              dispatch(
                updatePassenger(
                  id,
                  {
                    birth: '',
                    gender: '',
                    ticketType,
                    followAdult: undefined,
                  },
                  ['licenseNo']
                )
              );
            }
          }

          dispatch(hideMenu());
        },
        options: [
          {
            title: '成人票',
            value: 'adult',
            active: passager.ticketType === 'adult',
          },
          {
            title: '儿童票',
            value: 'child',
            active: passager.ticketType === 'child',
          },
        ],
      })
    );
  };
}

export function hideMenu() {
  return setIsMenuVisible(false);
}
